package com.greatmay.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.greatmay.service.RecommendationService;
import com.greatmay.dao.SearchException;
import com.greatmay.model.Recommendation;
import com.greatmay.webapp.action.BaseAction;

import java.util.List;

public class RecommendationAction extends BaseAction implements Preparable {
    private RecommendationService recommendationService;
    private List recommendations;
    private Recommendation recommendation;
    private Long id;
    private String query;

    public void setRecommendationService(RecommendationService recommendationService) {
        this.recommendationService = recommendationService;
    }

    public List getRecommendations() {
        return recommendations;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String recommendationId = getRequest().getParameter("recommendation.id");
            if (recommendationId != null && !recommendationId.equals("")) {
                recommendation = recommendationService.get(new Long(recommendationId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        try {
            recommendations = recommendationService.search(query, Recommendation.class);
        } catch (SearchException se) {
            addActionError(se.getMessage());
            recommendations = recommendationService.getAll();
        }
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Recommendation getRecommendation() {
        return recommendation;
    }

    public void setRecommendation(Recommendation recommendation) {
        this.recommendation = recommendation;
    }

    public String delete() {
    	recommendationService.remove(recommendation.getId());
        saveMessage(getText("recommendation.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            recommendation = recommendationService.get(id);
        } else {
            recommendation = new Recommendation();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (recommendation.getId() == null);

        recommendationService.save(recommendation);

        String key = (isNew) ? "recommendation.added" : "recommendation.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}